<?php
/**
 * 搜索基类队列
 *
 * @author: hjh <hjh@jf.com>
 *
 * Date: 2017/7/27
 * Time: 11:02
 */

require QUEUE_ROOT . 'lib/ElasticSearch.class.php';

class SearchBase extends Queue
{
    // 圈子
    const CIRCLE_SEARCH = 'meite_circle/list/';
    // 帖子
    const TOPIC_SEARCH = 'meite_topic/list/';
    // 评论
    const TOPIC_COMMENT_SEARCH = 'meite_comment/list/';


    protected static $SEARCH_INDEX = null;

    public function run($data)
    {
        $data = unserialize($data);
        if (count($data['data']) > 0) {
            $method = $data['type'];
            if (method_exists($this, $method)) {
                $this->$method($data['data']);
                return;
            }
        }

        $this->log(get_called_class(), $data);
    }

    protected function add($data)
    {
        assert(!empty(static::$SEARCH_INDEX));

        $query = static::$SEARCH_INDEX. $data['id'];

        $es = $this->getES();
        $ret = $es->query($query, ElasticSearch::HTTP_PUT, $data);
        if ($ret === false) {
            $this->log(get_called_class(), [
                'query' => $query,
                'data' => $data,
                'Error'
            ]);
        }
    }

    protected function update($data)
    {
        assert(!empty(static::$SEARCH_INDEX));

        $query = static::$SEARCH_INDEX . $data['id'] . '/_update';

        $es = $this->getES();
        $ret = $es->query($query, ElasticSearch::HTTP_POST, [
            'doc' => $data
        ]);
        if ($ret === false) {
            $this->log(get_called_class(), [
                'query' => $query,
                'data' => $data,
                'Error'
            ]);
        }
    }

    protected function delete($data)
    {
        assert(!empty(static::$SEARCH_INDEX));

        $query = static::$SEARCH_INDEX . $data['id'];
        $es = $this->getES();
        $ret = $es->query($query, ElasticSearch::HTTP_DELETE);
        if ($ret == false) {
            $this->log(get_called_class(), [
                'query' => $query,
                'data' => $data,
                'Error'
            ]);
        }
    }

    /**
     * 获取ES实例
     *
     * @return ElasticSearch
     */
    public function getES()
    {
        static $es = null;
        if ($es === null) {
            global $cfg;
            $config = $cfg['search']['default'];
            $es = new ElasticSearch($config);
        }

        return $es;
    }
}